from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse
import json
from card_api.models import Card, Comment, Collection, Likes
from django.core import serializers

# /api/card  title, content, user
# 接受前端post请求，将数据写入到数据库中
@csrf_exempt
def RecordCard(request):
    if request.method == 'POST':
        req = json.loads(request.body)
        title = req['title']
        content = req['content']
        user = req['user']
        new_card = Card(title=title, content=content, user=user, likes=0, comments=0, collections=0)
        new_card.save()
        return JsonResponse({"status": 200, "message": "写入成功"})


# /api/find   data:{find:'all'}  {title=}
@csrf_exempt
def GetCardInfos(request):
    if request.method == 'POST':
        req = json.loads(request.body)
        if "find" in req:  # 若find all为参数
            infos = Card.objects.all().order_by('-created_time')   # 默认为所有，且按照时间来排序，先发布的在上面
        elif "title" in req:
            infos = Card.objects.filter(title__contains=req['title']) # 模糊查询标题
        json_infos = serializers.serialize('json', infos)
        # json_infos = json.loads(json_infos)[0]
        # print(json_infos['fields'], type(json_infos))
        return HttpResponse(json_infos)

    elif request.method == 'GET':
        req = dict(request.GET)
        print("GetCardInfos:", req)
        card_id = req['card_id'][0]
        info = Card.objects.filter(id=card_id)
        json_infos = serializers.serialize('json', info)
        return HttpResponse(json_infos)

# 获取所有信息的
@csrf_exempt
def GetLikesInfos(request):
    if request.method == 'POST':
        req = json.loads(request.body)
        user_likes = Likes.objects.filter(user=req['user'])
        json_infos = serializers.serialize('json', user_likes)
        return HttpResponse(json_infos)

# 更新点赞状态，并且使点赞数-1
@csrf_exempt
def UpdateLikesStateAndNumber(request):
    if request.method == "POST":
        req = json.loads(request.body)
        print("req:", req)
        card_id = req['card_id']
        user = req['user']
        state = req['state']
        print(card_id, user, state)
        likes = Card.objects.filter(id=card_id).values('likes')  # 查询like数据
        likes = list(likes)[0]['likes']  # 转为能够读取的数据
        # json_infos = serializers.serialize('json', likes)
        if Likes.objects.filter(user=user, card_id=card_id): # 如果有点赞数据
            if state is True:  # 如果是已经点赞了的状态，则要取消点赞，并且对应的卡片赞数-1
                temp_state = False
                likes = likes - 1
            else:
                temp_state = True
                likes = likes + 1
            Likes.objects.filter(user=user, card_id=card_id).update(state=temp_state)  # 找到对应的位置，取消对应的点赞状态
            Card.objects.filter(id=card_id).update(likes=likes)  # 对应点赞数量减去1
        else:
            temp_user_likes = Likes(user=user, card_id=card_id, state=True)
            Card.objects.filter(id=card_id).update(likes=likes+1)  # 对应点赞数量加1
            temp_user_likes.save()
        return JsonResponse({"state": 200, "message": "更新成功"})


# 添加到用户的收藏夹
@csrf_exempt
def AddCollection(request):
    if request.method == 'POST':
        req = json.loads(request.body)
        print("req:", req)
        user = req['user']
        card_id = req['card_id']
        collections = Card.objects.filter(id=card_id).values('collections')  # 查询collections数据
        collections = list(collections)[0]['collections']  # 转为能够读取的数据
        res = Collection.objects.filter(user=user, card_id=card_id)  # 在数据库中寻找该用户是否收藏了该卡片
        state = '更新'
        if len(res) == 0:  # 如果没有,则保存
            r = Collection(user=user, card_id=card_id)
            collections += 1
            r.save()
        else:   # 如果找到了，则表示已经存了
            Collection.objects.filter(user=user, card_id=card_id).delete()  # 找到了则删除
            collections -= 1
            state = '删除'
        Card.objects.filter(id=card_id).update(collections=collections)
        return JsonResponse({"state": 200, "message": "收藏状态{}成功".format(state)})


@csrf_exempt
def GetUserCollectionInfos(request):
    if request.method == 'POST':
        req = json.loads(request.body)
        print(req)
        user_collections = Collection.objects.filter(user=req['user'])
        items = list(user_collections.values())
        ids = []
        print(items)
        for item in items:
            ids.append(item['card_id'])

        temp = Card.objects.filter(id__in=ids)  # 用in，以列表的形式获取数据
        json_info = serializers.serialize('json', temp)
        print("json_info:", json_info)
        return HttpResponse(json_info)

    if request.method == 'GET':
        print("request:", request)
        print(request.GET)
        req = dict(request.GET)
        user = req['user'][0]
        # print(req, req['user'][0])
        user_collections = Collection.objects.filter(user=user)
        json_infos = serializers.serialize('json', user_collections)
        print(json_infos)
        return HttpResponse(json_infos)


# 处理评论的API
@csrf_exempt
def CommentAPI(request):


    if request.method == 'POST':
        req = json.loads(request.body)
        card_comments = Card.objects.filter(id=req['card_id']).values("comments")
        card_comments = list(card_comments)[0]['comments']  # 评论数
        card_id = req['card_id']  # 要添加到的卡片
        comment = req['comment']  # 评论
        user = req['user']  # 谁发表的
        one_comment = Comment(card_id=card_id, comment=comment, user=user)
        one_comment.save()
        Card.objects.filter(id=card_id).update(comments=card_comments+1)
        return JsonResponse({"state": 200, "message": "评论发表成功"})

    elif request.method == 'DELETE':
        req = json.loads(request.body)
        card_comments = Card.objects.filter(id=req['card_id']).values("comments")
        card_comments = list(card_comments)[0]['comments']  # 评论数
        comment_id = req['pk']    # pk 是每一条评论的卡片id
        card_id = req['card_id']  # card_id是卡片的id
        Comment.objects.filter(id=comment_id).delete()
        Card.objects.filter(id=card_id).update(comments=card_comments - 1)
        return JsonResponse({"state": 200, "message": "评论删除成功"})

    elif request.method == 'GET':  # 获取卡片评论信息的请求
        req = dict(request.GET)
        print(req)
        card_id = req['card_id'][0]
        comment_infos = Comment.objects.filter(card_id=card_id)
        json_infos = serializers.serialize('json', comment_infos)
        return HttpResponse(json_infos)


